<template>
	<uni-popup ref="popup" class="get-phone-pop" type="bottom" @change="onChange">
		<view class="content">
			<view class="title">首次登录需要获取并绑定手机号</view>
			<uniForms class="form">
				<formListItem class="item" :label="'绑定手机号:'" :label-width="150" :type="'text'" :read-only="true" placeholder="请授权获取" :value="phoneNum"></formListItem>
			</uniForms>
			<button class="btn btn-orange" :plain="true" open-type="getPhoneNumber" @click="startGet" @getphonenumber="getPhoneNumber">授权获取手机号</button>
		</view>
	</uni-popup>
</template>

<script>
import uniPopup from '../uni-popup/uni-popup.vue';
import uniForms from '../uni-forms/uni-forms.vue';
import formListItem from '../form-list-item/form-list-item.vue';
export default {
	components: {
		uniPopup,
		uniForms,
		formListItem
	},
	props: {
		show: {
			type: Boolean,
			default: false
		}
	},
	watch: {
		show: function(newVal, oldVal) {
			// 显示或隐藏
			if (newVal) this.$refs.popup.open();
			else this.$refs.popup.close();
		}
	},
	data() {
		return {
			phoneNum: '' //电话号码
		};
	},
	methods: {
		startGet() {
			uni.showLoading({
				title: '加载中...',
				mask: true
			});
		},
		onChange(even) {
			// console.log("change",even)
			this.$emit('update:show', even.show);
		},
		getPhoneNumber(even) {
			// 获取手机号码信息回调
			console.log('获取手机号码回调', even);
			if (even.detail.errMsg == 'getPhoneNumber:ok') {
				let data = even.detail;
				this.$store
					.dispatch('bindPhone', {
						// "code": "string", //code登录
						encryptedData: data.encryptedData, // 包括敏感数据在内的完整用户信息的加密数据，详细见加密数据解密算法。
						ivStr: data.iv //加密算法的初始向量，详细见加密数据解密算法。
					})
					.then(res => {
						// 成功
						console.log('成功绑定', res);
						this.phoneNum = res;
						
						setTimeout(()=>{
							uni.showToast({
								icon:"success",
								mask:true,
								duration: 2000,
								title: '绑定成功'
							});
						},500)
						setTimeout(() => {
							this.$emit('update:show', false);
						}, 2000);
					});
			} else {
				uni.hideLoading();
				uni.showToast({
					icon:"none",
					mask:true,
					duration: 2000,
					title: '获取手机号码失败'
				});
			}
		}
	}
};
</script>

<style lang="scss" scoped>
.get-phone-pop {
	.content {
		padding: 20rpx 0rpx;
		width: 100%;
		background-color: #fff;
		display: flex;
		flex-direction: column;
		justify-content: center;
		align-items: center;
		.title {
			font-size: 36rpx;
			font-weight: bolder;
			color: #232323;
			text-align: center;
			// padding-top: 20rpx;
		}
		.form {
			width: 80%;
			padding: 0;
		}
		.btn {
			border: 0;
			width: 80%;
			padding: 20rpx;
			font-size: 34rpx;
		}
	}
}
</style>
